package com.hxkcloud.patient.activitys;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hyphenate.chat.EMClient;
import com.hxkcloud.patient.R;
import com.hxkcloud.patient.alarm.Alarms;
import com.hxkcloud.patient.beans.LogoutInfo;
import com.hxkcloud.patient.beans.VersionBean;
import com.hxkcloud.patient.beans.VersionInfo;
import com.hxkcloud.patient.beans.resultbeans.ObjectResultBean;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.UrlAddress;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.utils.BrightnessUtils;
import com.hxkcloud.patient.utils.SharedPreferenceUtil;
import com.hxkcloud.patient.utils.StringUtil;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by ray_lei on 2016/7/10.
 */
public class SettingActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = SettingActivity.class.getSimpleName();
    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;

    private RelativeLayout chagepwLayout;//密码修改
    private RelativeLayout feedbakLayout;//意见反馈
    private RelativeLayout serviceLayout;//服务条款
    private RelativeLayout checkversionLayout;//版本更新
    private TextView versionTV;

    private Button exitBtn;//退出登录

    private ObjectResultBean<LogoutInfo> resultBean;

    private ObjectResultBean<VersionInfo> versionInfo;
    private VersionBean versionBean;
    private String newVersionUrl = "";

    //两个按钮，下载更新
    private PopupWindow popup_easynotice;
    private TextView tv_easynotice_title;
    private TextView tv_easynotice_cancel;
    private TextView tv_easynotice_func;
    //一个按钮，最新版本
    private PopupWindow popup_easynotice1;
    private TextView tv_easynotice1_title;
    private TextView tv_easynotice1_func;


    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_LOGOUT_SUCCESS:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(R.string.logoutsuccess);
                }
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        delAlarms();
                        EMClient.getInstance().logout(true);//退出登录,此方法为同步方法，里面的参数 true 表示退出登录时解绑 GCM 或者小米推送的 token
                    }
                }.start();

//                MobclickAgent.onProfileSignOff();

                JPushInterface.setAlias(mContext, "", null);
                SharedPreferenceUtil.setIsrunning(mContext, false);
                SharedPreferenceUtil.setLoginPassword(mContext, "");
                removeAll();
                Intent intent = new Intent(this, LoginActivity.class);
                startActivity(intent);


                break;
            case MessageCode.NETWORKCODE_LOGOUT_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(R.string.logoutfail);
                }
                break;
            case MessageCode.NETWORKCODE_UPDATEVERSIONINFO_SUCCESS:
                if (msg.obj != null) {
                    versionInfo = (ObjectResultBean<VersionInfo>) msg.obj;
                    if (versionInfo.getData() != null) {
//                        if ("0".equals(versionBean.getData().getIsNewVersion())) {
//                            //不是最新版本
//                            toastMsg(versionBean.getData().getNewVersion());
//                        } else {
//                            toastMsg(getResources().getString(R.string.current_version_isnew));
//                        }
                        popup_easynotice1.showAtLocation(ll_title, Gravity.CENTER, 0, 0);
                        BrightnessUtils.lightOff(this);
                    }
                }
                break;
            case MessageCode.NETWORKCODE_UPDATEVERSIONINFO_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                    return;
                }
                break;
            case MessageCode.NETWORKCODE_GETVERSION_SUCCESS:
                if (msg.obj != null) {
                    versionBean = (VersionBean) msg.obj;
                    String localName = getVersionName(mContext);
                    int i = localName.compareTo(versionBean.getVersion());
                    Log.i(TAG,"localName = "+localName);
                    Log.i(TAG,"versionBean.getVersion() = "+versionBean.getVersion());
                    Log.i(TAG,"i = "+i);

                    if (i>=0) {
                        popup_easynotice1.showAtLocation(ll_title, Gravity.CENTER, 0, 0);
                        BrightnessUtils.lightOff(this);
                    } else {
                        tv_easynotice_title.setText("是否更新为最新版本" + versionBean.getVersion());
                        tv_easynotice_cancel.setText(R.string.cancel);
                        tv_easynotice_func.setText(R.string.updateversion);
                        newVersionUrl = versionBean.getDownloadUrl();
                        popup_easynotice.showAtLocation(ll_title, Gravity.CENTER, 0, 0);
                        BrightnessUtils.lightOff(this);
                    }
                }
                break;
            case MessageCode.NETWORKCODE_GETVERSION_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                    return;
                }
                break;
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout_setting);
        initView();
        initPopup();
        initData();
        initListener();
    }

    @Override
    protected void initView() {
        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);

        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);
        tv_title.setText(getResources().getText(R.string.mine_text_setting));
        iv_back.setOnClickListener(this);

        chagepwLayout = (RelativeLayout) findViewById(R.id.setting_layout_changepw);
        feedbakLayout = (RelativeLayout) findViewById(R.id.setting_layout_feedback);
        serviceLayout = (RelativeLayout) findViewById(R.id.setting_layout_service);
        checkversionLayout = (RelativeLayout) findViewById(R.id.setting_layout_checkversion);
        versionTV = (TextView) findViewById(R.id.setting_btn_currentversion);
        exitBtn = (Button) findViewById(R.id.setting_btn_exit);
    }

    private void initPopup() {
//easynotice
        popup_easynotice = new PopupWindow(this);
        View viewNotice = LayoutInflater.from(this).inflate(R.layout.popup_easynotice, null);
        popup_easynotice.setContentView(viewNotice);

        popup_easynotice.setWidth((int) (screenWidth * 0.7));
        popup_easynotice.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup_easynotice.setFocusable(true);
        popup_easynotice.setTouchable(true);
        popup_easynotice.setOutsideTouchable(true);
        popup_easynotice.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popup_easynotice.setAnimationStyle(R.style.popupwindow_anim_alpha);

        tv_easynotice_title = (TextView) viewNotice.findViewById(R.id.tv_easynotice_title);
        tv_easynotice_cancel = (TextView) viewNotice.findViewById(R.id.tv_easynotice_cancel);
        tv_easynotice_func = (TextView) viewNotice.findViewById(R.id.tv_easynotice_func);

        tv_easynotice_title.setText(R.string.current_version_notnew);
        tv_easynotice_cancel.setOnClickListener(this);
        tv_easynotice_func.setOnClickListener(this);

        popup_easynotice.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                BrightnessUtils.lightOn(SettingActivity.this);
            }
        });

        //easynotice1
        popup_easynotice1 = new PopupWindow(this);
        View viewNotice1 = LayoutInflater.from(this).inflate(R.layout.popup_easynotice1, null);
        popup_easynotice1.setContentView(viewNotice1);

        popup_easynotice1.setWidth((int) (screenWidth * 0.7));
        popup_easynotice1.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup_easynotice1.setFocusable(true);
        popup_easynotice1.setTouchable(true);
        popup_easynotice1.setOutsideTouchable(true);
        popup_easynotice1.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popup_easynotice1.setAnimationStyle(R.style.popupwindow_anim_alpha);

        tv_easynotice1_title = (TextView) viewNotice1.findViewById(R.id.tv_easynotice1_title);
        tv_easynotice1_func = (TextView) viewNotice1.findViewById(R.id.tv_easynotice1_func);

        tv_easynotice1_title.setText(R.string.current_version_isnew);

        tv_easynotice1_func.setOnClickListener(this);

        popup_easynotice1.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                BrightnessUtils.lightOn(SettingActivity.this);
            }
        });
    }

    @Override
    protected void initListener() {

        iv_back.setOnClickListener(this);
        chagepwLayout.setOnClickListener(this);
        feedbakLayout.setOnClickListener(this);
        serviceLayout.setOnClickListener(this);
        checkversionLayout.setOnClickListener(this);
        exitBtn.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        versionTV.setText(getResources().getString(R.string.setting_text_version) + getVersionName(this));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back:
                finish();
                break;
            case R.id.setting_layout_changepw:
                Intent changpwIntent = new Intent(this, ChangePwActivity.class);
                startActivity(changpwIntent);
                break;
            case R.id.setting_layout_feedback://意见反馈
                Intent feedbackIntent = new Intent(this, FeedbackActivity.class);
                startActivity(feedbackIntent);
                break;
            case R.id.setting_layout_service://服务条款
                Intent intent = new Intent(SettingActivity.this, WebActivity.class);
                intent.putExtra("url", UrlAddress.H5_TIAOKUAN_URL);
                intent.putExtra("title", mContext.getResources().getString(R.string.setting_text_service));
                startActivity(intent);
                break;
            case R.id.setting_layout_checkversion://版本更新
//                YiJiaHuNetWorkUtils.checkVersionInfo(getVersionName(this), handler);
                StringUtil.zhugeTrack(mContext, "设置中版本更新按钮", "设置中版本更新按钮点击数");

                loading();
                YiJiaHuNetWorkUtils.getVersion(handler);
                break;
            case R.id.setting_btn_exit://退出登录
                loading();
                YiJiaHuNetWorkUtils.logout(handler);

                break;
            case R.id.tv_easynotice1_func:
                popup_easynotice1.dismiss();
                break;
            case R.id.tv_easynotice_cancel:
                popup_easynotice.dismiss();
                break;
            case R.id.tv_easynotice_func:
                popup_easynotice.dismiss();
                if (!TextUtils.isEmpty(newVersionUrl)) {
//                    toastMsg("down");
                    Uri url = Uri.parse(newVersionUrl);
                    Intent intentUrl = new Intent(Intent.ACTION_VIEW, url);
                    startActivity(intentUrl);

                    SharedPreferenceUtil.setIsrunning(mContext, false);
                    SharedPreferenceUtil.setLoginPassword(mContext, "");
                } else {
                    toastMsg(R.string.downloadurl_wrong);
                }
                break;
        }

    }

    //alarm function
    private void delAlarms() {
//        Cursor mCursor;
//        mCursor = Alarms.getAlarmsCursor(this
//                .getContentResolver());
//        while (mCursor.moveToNext()) {
//            Alarm alarm2 = new Alarm(mCursor);
//            Alarms.deleteAlarm(this, alarm2.id);
//        }
        Alarms.clearAlarm(this);
    }

    //版本名
    public static String getVersionName(Context context) {
        return getPackageInfo(context).versionName;
    }

    //版本号
    public static int getVersionCode(Context context) {
        return getPackageInfo(context).versionCode;
    }

    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }

}
